package dao.JPA;

import javax.persistence.EntityManager;

import dao.JPAFactoryDAO;
import bean.Cliente;
import interfaces.ClienteInt;

/**
 * 
 * @author Daniel Rodrigues
 */
public class JPAClienteDAO implements ClienteInt {

	@Override
	public void inserir(Cliente cliente) {
		EntityManager em = JPAFactoryDAO.getInstance().getFactory()
				.createEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(cliente);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			em.close();
		}
	}

	@Override
	public void alterar(Cliente cliente) {
		EntityManager em = JPAFactoryDAO.getInstance().getFactory()
				.createEntityManager();
		try {
			em.getTransaction().begin();
			em.merge(cliente);
			em.getTransaction().commit();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			em.close();
		}

	}

	@Override
	public void deletar(Cliente cliente) {
		EntityManager em = JPAFactoryDAO.getInstance().getFactory()
				.createEntityManager();
		try {
			em.remove(cliente);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			em.close();
		}

	}

	@Override
	public Cliente consultar(long id) {
		EntityManager em = JPAFactoryDAO.getInstance().getFactory()
				.createEntityManager();
		Cliente cliente = null;
		try {
			cliente = (Cliente) em.find(Cliente.class, id);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		em.close();
		return cliente;
	}

	@Override
	public Cliente consultarClientePorNome(String nome) {
		// TODO Auto-generated method stub
		return null;
	}

}
